<?php

define('DEMO_CURL_VERBOSE', false); // 打印curl debug信息

include_once __DIR__."/../init.php";

$config = array_merge($defaults,array());
$files = getfiles(__DIR__."/../../sample/1x");

// var_dump($config);
// var_dump($files);

function asr($file){
  // var_dump($file);
  echo 'asr file:'.$file['filename'].PHP_EOL;

  $url = "http://api.xfyun.cn/v1/service/v1/iat";

  $appid = '5ac98d18';
  $apikey = '9633baf90036b61eaf08fd629a5cc19e';
  $ctime = time();
  // $appid = '5ac306e3';
  $param = array(
    'engine_type'=>'sms16k',
    // 'auf'=>'8k',
    'aue'=>'raw',
    // 'scene'=>'main'
  );

  $xparam = base64_encode(json_encode($param));

  $audio = file_get_contents($file['filepath']);
  $base_data = base64_encode($audio);
  
  $body = 'audio='.$base_data;

  $headers[] = 'X-Appid:'.$appid;
  $headers[] = 'X-CurTime:'.$ctime;
  $headers[] = 'X-Param:'.$xparam;
  $headers[] = 'X-CheckSum:'.md5($apikey.$ctime.$xparam);
  $headers[] = 'Content-Type:application/x-www-form-urlencoded; charset=utf-8';

  // var_dump($headers);

  $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	curl_setopt($ch, CURLOPT_TIMEOUT, 120); // 识别时长不超过原始音频
  curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  // curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式  
  // curl_setopt($ch, CURLOPT_PROXY, "203.174.112.13"); //代理服务器地址   
  // curl_setopt($ch, CURLOPT_PROXYPORT,3128); //代理服务器端口
  curl_setopt($ch, CURLOPT_VERBOSE, DEMO_CURL_VERBOSE);
  
  // list($msec, $sec) = explode(' ', microtime());
  // $time = intval($sec) + floatval($msec);

  $res = curl_exec($ch);
  // list($msec, $sec) = explode(' ', microtime());
  // $time = intval($sec) + floatval($msec) - $time;
  if(false === $res){
    $errno = curl_errno($ch);
    if($errno == 0){
      $errno = -1;
    }
    $msg = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    echo $msg;
    return;
    // curl_close($ch);
    // exit;
  }
  
  

  curl_close($ch);
  echo 'response:'.$res.PHP_EOL;

  // $ddd = array(
  //   'time'=>sprintf("%.4f",$time),
  //   'response'=>json_decode($res,true)
  // );

  put_rusult(__DIR__.'/../../result/xunf/'.$file['filename'].'.txt', $res);
  // var_dump($res);

	// echo "Token URL response is " . $res . "\n";
	// $response = json_decode($res, true);
}

try{
  foreach($files as $file){
    asr($file);
    // if('2-2' == $file['filename']){
      // asr($file);
      // break;
    // }
    
  }
}catch(Exception $e){
  var_dump($e);
}


?>